import * as React from 'react';
import produce from 'immer'
import { IComponent } from '@bastet/widgets';
import { createInformationFunc, createFunc } from "./func";


export type Information = {
  index: any[],
  data: IComponent
}

interface IReducerStateParams {
  value: any; field: string; index: string
}
function reducerState(state: IComponent, action: IComponent): IComponent {
  console.log('%cnextState:after', 'background: goldenrod;', action)
  return action || state
}

export function useStateReducer() {
  const [state, dispatch] = (React.useReducer as any)(reducerState, [])

  const changeField = ({ value, field, index }: IReducerStateParams) => {
    const __index = index.split('-');
    console.log('nextState:before', { value, field, index }, __index)
    const nextState = produce(state, (draft: IComponent[]) => {
      const func = createInformationFunc(__index as any);

      console.log('createInformationFunc', func, draft)
      func(draft, (data: any) => {
        console.log('createInformationFunc', data)
        if (data) {
          if(field.indexOf('.') > -1) {
            try {
              const execFunc = new Function('data', 'path', 'val', `data.${field} = val`)
              execFunc(data.renderProps, field, value)
            } catch (e) {
              console.error(`“${field}” 在 renderProps 上找不到，无法赋值，请检查代码！\r\n`, e)
            }
          } else {
            data.renderProps[field] = value
          }
        }

        return data
      })
    });

    dispatch(nextState as any)
  }

  const changeWidget = ({ value, field, index }: IReducerStateParams) => {
    const __index = index.split('-');
    console.log('nextState:before', { value, field, index }, __index)
    const nextState: any = produce(state, (draft: any) => {
      const func = createFunc(targetIndexArray as any);
      let prevComponents: any;
      console.log(func)
      func(draft, (components: IComponent[]) => {
        console.log('components', components)
        if (!components) return  components
        if (index <= 0) {
          components.unshift(data)
        } else if (index > 0) {
          components.splice(+index, 0, data)
        }

        prevComponents = components;
        return components
      })

      if (originIndex) {
        // 来源下标转数组
        const originIndexArray = originIndex?.split('-') || [];
        // 删除来源目标下标位置
        const removeIndex = originIndexArray.pop();
        const removeFunc = createFunc(originIndexArray as any);

        // 去掉最后一位
        // 0 -> ''
        // 0-1 -> '0'
        // 0-1-3 -> '0-1'
        removeFunc(draft, (components: IComponent[]) => {
          if (!components) return  components
          components.splice(removeIndex, 1);

          console.log('prevComponents', prevComponents, components)
          console.log('prevComponents', prevComponents.toString(), components.toString(), prevComponents.toString() === components.toString())
          if (prevComponents.toString() === components.toString()) {
            isUpdate = false;
          }
          console.log('components', components)
          return components
        })
      }
    });

    dispatch(nextState as any)
  }

  return [state, changeWidget, changeField]
}

let informationDefault: Information // = originalState.children[0] as Information;
function reducerInfo(state: Information[], action: any) {
  return action || state
}

export function useInformationReducer<T>(defData: IComponent[]): [T, any] {
  const [information, dispatch] = React.useReducer<any>(reducerInfo, informationDefault || defData)

  return [information as T, dispatch]
}